from django.shortcuts import render
import json
import re

from django.contrib.auth import login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError
from django.http import HttpResponse
from django.http import JsonResponse
from django import http
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View


from apps import ausers
from apps.ausers.models import User, Address
from apps.ausers.utils import generate_verify_email_url
from apps.carts.utils import merge_cart_cookie_to_redis
from apps.goods.models import SKU
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE
from django_redis import get_redis_connection

from utils.secret import SecretOauth

class FindPassword(View):
    def get(self,request):
        return render(request,'find_password.html')

class UserNameVerify(View):
    def get(self,request,username):
        image_code = request.GET.get('text')
        if not all([username, image_code]):
            return http.HttpResponseForbidden('参数不全')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseForbidden('重新输入用户名')
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return http.HttpResponseNotFound({'code': 404, 'errmsg': '用户不存在'})
        uuid = request.GET.get('image_code_id')
        img_redis = get_redis_connection('image_codes')
        redis_get_uuid = img_redis.get('img_%s' % uuid)
        if redis_get_uuid is None:
            return http.HttpResponseBadRequest({'code': 400, 'errmsg': '图形验证码有误'})
        if image_code.lower() != redis_get_uuid.decode().lower():
            return http.HttpResponseBadRequest({'code': 400, 'errmsg': '图形验证码有误'})
        img_redis.delete('img_%s' % uuid)

        mobile = user.mobile
        access_token = user.id
        redis_client = get_redis_connection('access_token')
        redis_client.setex('access_token',300,access_token)
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK','mobile':mobile,
            'access_token':access_token})

class SmsCodes(View):
    def get(self,request):
        access_token = request.GET.get('access_token')
        user = User.objects.get(id=access_token)
        mobile = user.mobile
        user_id = user.id
        from random import randint
        sms_code = randint(100000, 999999)
        sms_red_cline = get_redis_connection('sms_codes')
        # 校验短信验证码
        sms_redis_get = sms_red_cline.get('flge_%s' % mobile)
        print(sms_redis_get)
        if sms_redis_get is None:
            p1 = sms_red_cline.pipeline()
            p1.setex('flge_%s' % mobile, 60, 1)
            p1.setex("sms_%s" % mobile, 300, sms_code)
            p1.execute()
            from celery_tasks.sms.tasks import ccp_send_sms_code
            ccp_send_sms_code.delay(mobile, sms_code)
            print(sms_code)
            # 5.告诉前端短信发送完毕
            return http.JsonResponse({'code': '0', 'errmsg': '发送短信成功',
                                      'user_id':user_id,'access_token':access_token})
        else:
            return http.HttpResponseBadRequest({'code': '400', 'message': '请勿频繁发送'})

class SmsCodesVerify(View):
    def get(self,request,username):
        sms_code = request.GET.get('sms_code')
        access_token = User.objects.get(username=username)
        mobile = access_token.mobile
        user_id = access_token.id
        userid = access_token.id
        sms_redis = get_redis_connection('sms_codes')
        sms_redis_code = sms_redis.get("sms_%s" % mobile)
        if sms_redis_code is None:
            return http.HttpResponseBadRequest({'code': '400', 'errmsg': '短信验证码有误'})
        if sms_code != sms_redis_code.decode():
            return http.HttpResponseBadRequest({'code': '400', 'errmsg': '短信验证码有误'})
        login(request, access_token)
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK',
                                  'user_id':user_id,'access_token':userid})


class UpdataPW(View):
    def post(self,request,user_id):
        user = User.objects.get(id=user_id)
        if user is None:
            return http.HttpResponseForbidden('用户不存在')
        json_dict = json.loads(request.body.decode())
        password = json_dict.get('password')
        password2= json_dict.get('password2')
        access_token = json_dict.get('access_token')
        if not all ([password,password2,access_token]):
            return http.HttpResponseForbidden('参数不全')
        if not re.match(r'^\d+$',password):
            return http.HttpResponseForbidden('用户信息非法')
        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.HttpResponseForbidden('密码非法')
        if password2 != password:
            return http.HttpResponseForbidden('密码不一致')
        redis_client = get_redis_connection('access_token')
        user_vrief = redis_client.get('access_token')
        id = int(user_vrief.decode())
        if access_token != id:
            return http.HttpResponseForbidden('操作非法')
        redis_client.delete('access_token')
        try:
            request.user.set_password(password)
            request.user.save()
        except Exception as e:
            logger.info(e)
            return render(request, 'find_password.html', {'change_pwd_errmsg': '修改密码失败'})
        logout(request)
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK'})


